package com.mx.recycleview.recycleview

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.mx.recycleview.manager.CoverFlowLayoutManger
import com.mx.recycleview.manager.CoverFlowLayoutManger.OnSelected

/**
 * 继承RecyclerView重写[.getChildDrawingOrder]对Item的绘制顺序进行控制
 *
 * @author Chen Xiaoping (562818444@qq.com)
 * @version V1.0
 * @Datetime 2017-04-18
 */
open class RecyclerCoverFlow @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
    /**
     * 按下的X轴坐标
     */
    private var mDownX = 0f

    /**
     * 布局器构建者
     */
    private val mManagerBuilder = CoverFlowLayoutManger.Builder()

    init {
        layoutManager = mManagerBuilder.build()
        isChildrenDrawingOrderEnabled = true //开启重新排序
        overScrollMode = View.OVER_SCROLL_NEVER
    }

    /**
     * 设置是否为普通平面滚动
     * @param isFlat true:平面滚动；false:叠加缩放滚动
     */
    fun setFlatFlow(isFlat: Boolean) {
        mManagerBuilder.setFlat(isFlat)
        layoutManager = mManagerBuilder.build()
    }

    /**
     * 设置Item灰度渐变
     * @param greyItem true:Item灰度渐变；false:Item灰度不变
     */
    fun setGreyItem(greyItem: Boolean) {
        mManagerBuilder.setGreyItem(greyItem)
        layoutManager = mManagerBuilder.build()
    }

    /**
     * 设置Item灰度渐变
     * @param alphaItem true:Item半透渐变；false:Item透明度不变
     */
    fun setAlphaItem(alphaItem: Boolean) {
        mManagerBuilder.setAlphaItem(alphaItem)
        layoutManager = mManagerBuilder.build()
    }

    fun setLoop(loop: Boolean = true) {
        mManagerBuilder.loop(loop)
        layoutManager = mManagerBuilder.build()
    }

    /**
     * 设置Item的间隔比例
     * @param intervalRatio Item间隔比例。
     * 即：item的宽 x intervalRatio
     */
    fun setIntervalRatio(intervalRatio: Float) {
        mManagerBuilder.setIntervalRatio(intervalRatio)
        layoutManager = mManagerBuilder.build()
    }

    fun setDebug(debug: Boolean = true) {
        mManagerBuilder.debug(debug)
        layoutManager = mManagerBuilder.build()
    }

    override fun setLayoutManager(layout: LayoutManager?) {
        require(layout is CoverFlowLayoutManger) { "The layout manager must be CoverFlowLayoutManger" }
        super.setLayoutManager(layout)
    }

    public override fun getChildDrawingOrder(childCount: Int, i: Int): Int {
        val coverFlowLayout = coverFlowLayout ?: return i
        val center = coverFlowLayout.centerPosition
        // 获取 RecyclerView 中第 i 个 子 view 的实际位置
        val actualPos = coverFlowLayout.getChildActualPos(i)
        // 距离中间item的间隔数
        val dist = actualPos - center
        var order: Int
        order = if (dist < 0) { // [< 0] 说明 item 位于中间 item 左边，按循序绘制即可
            i
        } else { // [>= 0] 说明 item 位于中间 item 右边，需要将顺序颠倒绘制
            childCount - 1 - dist
        }
        if (order < 0) order = 0 else if (order > childCount - 1) order = childCount - 1
        return order
    }

    /**
     * 获取LayoutManger，并强制转换为CoverFlowLayoutManger
     */
    val coverFlowLayout: CoverFlowLayoutManger?
        get() = layoutManager as CoverFlowLayoutManger?

    /**
     * 中心位置，跟设置的adapt的item数量无关
     */
    val centerPosition = coverFlowLayout?.centerPosition ?: 0

    fun smoothScrollToNext(size: Int = 1) {
        coverFlowLayout?.smoothScrollToNext(size)
    }

    fun smoothScrollToPre(size: Int = 1) {
        coverFlowLayout?.smoothScrollToPre(size)
    }

    /**
     * 获取被选中的Item位置
     */
    val selectedPos: Int?
        get() = coverFlowLayout?.selectedPos

    /**
     * 设置选中监听
     * @param l 监听接口
     */
    fun setOnItemSelectedListener(l: OnSelected?) {
        mManagerBuilder.setOnItemSelect(l)
        layoutManager = mManagerBuilder.build()
    }

    // TODO：触摸拦截
//    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
//        val coverFlowLayout = coverFlowLayout ?: return super.dispatchTouchEvent(ev)
//
//        when (ev.action) {
//            MotionEvent.ACTION_DOWN -> {
//                mDownX = ev.x
//                parent.requestDisallowInterceptTouchEvent(true) //设置父类不拦截滑动事件
//            }
//            MotionEvent.ACTION_MOVE -> {
//                if (mManagerBuilder.isLoop) {
//                    parent.requestDisallowInterceptTouchEvent(true)
//                } else {
//                    if ((ev.x > mDownX && coverFlowLayout.centerPosition == 0) ||
//                        (ev.x < mDownX && coverFlowLayout.centerPosition == coverFlowLayout.itemCount - 1)
//                    ) {
//                        //如果是滑动到了最前和最后，开放父类滑动事件拦截
//                        parent.requestDisallowInterceptTouchEvent(false)
//                    } else {
//                        //滑动到中间，设置父类不拦截滑动事件
//                        parent.requestDisallowInterceptTouchEvent(true)
//                    }
//                }
//            }
//        }
//        return super.dispatchTouchEvent(ev)
//    }
}